package com.ebt.m.wiki;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListPopupWindow;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.ebt.m.AppContext;
import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.activity.BaseToolBarActivity;
import com.ebt.m.commons.model.data.BaseDataResult;
import com.ebt.m.commons.utils.ToastUtil;
import com.ebt.m.config.CustomerConfig;
import com.ebt.m.data.bean.CommonCustomer;
import com.ebt.m.data.bean.UserInfo;
import com.ebt.m.data.entity.CompanyInfo;
import com.ebt.m.data.entity.NewProductInfo;
import com.ebt.m.data.entity.ProductBridgeObj;
import com.ebt.m.data.entity.ProductInfo;
import com.ebt.m.data.entity.ProductInfoBridge;
import com.ebt.m.data.middle.InsuranceObj;
import com.ebt.m.data.middle.InsuredPerson;
import com.ebt.m.data.middle.PolicyNodeMeta;
import com.ebt.m.data.middle.ProductDatainfo;
import com.ebt.m.data.middle.datatype.EController;
import com.ebt.m.data.provider.WikiProvider;
import com.ebt.m.data.rxModel.apibean.ApiProduct;
import com.ebt.m.proposal_v2.utils.ProposalUtils;
import com.ebt.m.utils.DataValidation;
import com.ebt.m.utils.MathUtil;
import com.ebt.m.utils.TimeUtils;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.utils.android.ConnectionDetector;
import com.ebt.m.utils.android.DownloaderConstants;
import com.ebt.m.utils.android.ProductDownloader;
import com.ebt.m.view.CircleImageView;
import com.ebt.m.widget.SlidingTabLayout;
import com.ebt.m.wiki.adapter.ListPopupWindowAdapter;
import com.ebt.m.wiki.event.EData4Cal;
import com.ebt.m.wiki.event.EOnCalculatorChange;
import com.jakewharton.rxbinding2.view.RxView;
import com.tendcloud.tenddata.TCAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @author Damon.Han
 * @Description:产品详情页面
 * @date 2015年12月18日 上午11:37:18
 */
public class ActProductDetail extends BaseToolBarActivity {
    private int data_from;//判断数据来源

    private Context mContext;
    private SlidingTabLayout mSlidingTabLayout;
    private ProgressDialog progressDialog4Download;
    private ViewPager mViewPager;
    //案例
    private FrameLayout case_container;
    private TextView customr_common;
    private TextView txtCname;
    private TextView txtName;
    private TextView txtAge;
    private TextView txtSex;
    private TextView txtCate;
    private View viewCoverageTitle;
    private View viewCoverageContent;
    private TextView txtCoverage;
    private TextView txtPremiumTitle;
    private TextView txtPremium;
    private TextView txtPP;
    private TextView txtProtect;
    private View toCal;
    //----------------常用客户选择弹窗-------------------
    ListPopupWindow mListPopupWindow;

    private MPagerAdapter mAdapter;
    private ProductInfo mProductInfo;
    private CompanyInfo currentCompany;
    private ProductBridgeObj mProductObj;
    private WikiProvider dataProvider;


    List<String> titles = new ArrayList<String>();

    /**/
    FrgProductDesc frgProductDesc;
    FrgProductRule frgProductRule;
    FrgProductClause fpc;
    FrgProductTable2 frgProductTable2;
    private HashMap<String, Double> rateHashMap;

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.wiki_product_detail);
        initView();
        initData();
        /* 订阅 */
        EventBus.getDefault().register(this);
    }

    private void initView() {
        case_container = (FrameLayout) findViewById(R.id.case_container);
    }

    private void initCaseView(View view) {
        txtCname = (TextView) view.findViewById(R.id.cname);
        txtName = (TextView) view.findViewById(R.id.name);
        txtAge = (TextView) view.findViewById(R.id.age);
        txtSex = (TextView) view.findViewById(R.id.sex);
        txtCate = (TextView) view.findViewById(R.id.cate);
        txtCoverage = (TextView) view.findViewById(R.id.coverage);
        viewCoverageTitle = view.findViewById(R.id.coverage_area_content);
        viewCoverageContent = view.findViewById(R.id.coverage_area_head);
        txtPremiumTitle = (TextView) view.findViewById(R.id.premium_title);
        txtPremium = (TextView) view.findViewById(R.id.premium);
        txtPP = (TextView) view.findViewById(R.id.payment_period);
        txtProtect = (TextView) view.findViewById(R.id.protect);
        toCal = view.findViewById(R.id.to_cal);
        RxView.clicks(toCal)
                .throttleFirst(400, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    toCalc();
                });
    }

    private void initData() {
        dataProvider = new WikiProvider(mContext);
        Bundle bundle = getIntent().getExtras();
        if (bundle == null) {
            return;
        }
        mProductInfo = (ProductInfo) bundle.getSerializable(ProductBridgeObj.KEY_OBJ);
        currentCompany = (CompanyInfo) bundle.getSerializable("currentCompany");
        data_from = bundle.getInt("data_from", 0);
        //不管是否是本地产品都在线获取产品信息
        if (mProductInfo != null) {
            getProductInfoOnLine(mProductInfo.ProductId);
        } else {
            NewProductInfo newProductInfo = (NewProductInfo) bundle.getSerializable("newProductInfo");
            if (newProductInfo != null) {
                getProductInfoOnLine(newProductInfo.getProductId());
            } else {
                int productId = bundle.getInt("productId");
                if (productId > 0) {
                    getProductInfoOnLine(productId);
                }
            }
        }

    }

    private void initBasicData() {
        //保存浏览记录
//        dataProvider.insertProductBrowse(mProductInfo);
        HashMap kv = new HashMap();
        kv.put("product_id", String.valueOf(mProductInfo.Id));
        kv.put("product_name", mProductInfo.Name);
        UserInfo userInfo = AppContext.getCurrentUser();
        kv.put("agentId", String.valueOf(userInfo.getUserId()));
        kv.put("account", userInfo.getUserName());
        TCAgent.onEvent(mContext, "open_product", "", kv);
        String titless[] = mContext.getResources().getStringArray(R.array.product_detail_titles);
        for (int i = 0; i < titless.length; i++) {
            titles.add(titless[i]);
        }
        if (mProductInfo.ShortName != null) {
            setTitle(mProductInfo.ShortName);
        }

        onLineOperation();
    }

    /**
     * 获取产品描述信息
     *
     * @param productId 产品id
     */
    private void getProductInfoOnLine(int productId) {
        progressDialog4Download = new ProgressDialog(this);
        progressDialog4Download.setTitle("请稍候");
        progressDialog4Download.setMessage(getResources().getString(R.string.download_hint));
        progressDialog4Download.setIndeterminate(false);
        progressDialog4Download.setCancelable(false);
        progressDialog4Download.setCanceledOnTouchOutside(false);
        progressDialog4Download.setOnCancelListener(null);
        progressDialog4Download.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        progressDialog4Download.show();
        int state = ConnectionDetector.getNetStatus();
        switch (state) {
            case 1://wifi
            case 2://mobile
                AppInitService.getEbtApi().getProductFromAPI(productId)
                        .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<BaseDataResult<ApiProduct>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseDataResult<ApiProduct> dataResult) {
                        if (dataResult != null && dataResult.getData() != null) {
                            mProductInfo = ProductInfoBridge.getProductInfoFromApi(dataResult.getData());
                            List<ApiProduct.ProductObjBean> list = dataResult.getData().getProductObj();
                            String valueJsonStr = "";
                            for (int i = 0; i < list.size(); i++) {
                                ApiProduct.ProductObjBean objBean = list.get(i);
                                if ("RateTable".equalsIgnoreCase(objBean.getFieldName())) {
                                    valueJsonStr = objBean.getValueJsonStr();
                                    break;
                                }
                            }
                            try {
                                JSONObject jsonObject = new JSONObject(valueJsonStr);
                                if (jsonObject == null) {
                                    return;
                                }
                                String rateType = null;
                                if (jsonObject.has("valueType")) {
                                    rateType = jsonObject.getString("valueType");
                                    mProductInfo.setRateType(rateType);
                                }
                                if (rateType != null && "object".equalsIgnoreCase(rateType)) {
                                    //年龄
                                    for (int i = 0; i < list.size(); i++) {
                                        ApiProduct.ProductObjBean objBean = list.get(i);
                                        if ("PIAge".equalsIgnoreCase(objBean.getFieldName())) {
                                            valueJsonStr = objBean.getValueJsonStr();
                                            break;
                                        }
                                    }
                                    jsonObject = new JSONObject(valueJsonStr);
                                    int age = jsonObject.getInt("value");
                                    //性别
                                    for (int i = 0; i < list.size(); i++) {
                                        ApiProduct.ProductObjBean objBean = list.get(i);
                                        if ("PISex".equalsIgnoreCase(objBean.getFieldName())) {
                                            valueJsonStr = objBean.getValueJsonStr();
                                            break;
                                        }
                                    }
                                    jsonObject = new JSONObject(valueJsonStr);
                                    int sex = jsonObject.getInt("value");
                                    getOnlineRate(age, sex, dataResult.getData().getProductId(), 0);
                                } else {
                                    initBasicData();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        ToastUtil.show(mContext, "产品打开失败，请重试!");
                        finish();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
                break;
            default:
                UIHelper.makeToast(mContext, mContext.getString(R.string.network_fail));
                finish();
                break;
        }

    }

    /**
     * 获取rate
     *
     * @param age
     * @param sex
     * @param productId
     */
    private void getOnlineRate(int age, int sex, int productId, int flag) {
        AppInitService.getEbtApi().getRate(productId, age + "", sex + "")
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<BaseDataResult<HashMap<String, Double>>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseDataResult<HashMap<String, Double>> hashMapBaseDataResult) {
                rateHashMap = hashMapBaseDataResult.getData();
                if (rateHashMap == null) {
                    return;
                }
                if (flag == 0) {
                    initBasicData();
                } else {
                    setCaseInfo();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void initOnline() {
        if (progressDialog4Download != null) {
            progressDialog4Download.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ProductDownloader.cancel(mProductInfo.Id, mProductInfo.CompanyId);
                    finish();
                }
            });
        }
        Handler handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case DownloaderConstants.DOWNLOAD_STATE_DONE:
                        Bundle data = msg.getData();
                        int productVersion = data.getInt("ProductVersion", mProductInfo.ProductVersion);
                        int resVersion = data.getInt("ResourceVersion", mProductInfo.ResourceVersion);
                        mProductInfo.ProductVersion = productVersion;
                        mProductInfo.LocalProductVersion = productVersion;
                        mProductInfo.ResourceVersion = resVersion;
                        mProductInfo.LocalResourceVersion = resVersion;
//                        FrontProvider.updateProductToLocal(mProductInfo.Id, productVersion, resVersion);
                        ProductDownloader.removeDownloadProductThread(mProductInfo.ProductId);
//                        setProduct2Local(mProductInfo.Id);
                        try {
                            mProductObj = new ProductBridgeObj(mProductInfo, rateHashMap);
                            initTab();
                        } catch (Exception e) {
                            e.printStackTrace();
                            UIHelper.makeToast(mContext, mContext.getString(R.string.network_fail));
                            finish();
                        }
                        if (progressDialog4Download != null && progressDialog4Download.isShowing()) {
                            progressDialog4Download.dismiss();
                        }
                        break;
                    case DownloaderConstants.DOWNLOAD_STATE_FAILED:
                        if (progressDialog4Download != null && progressDialog4Download.isShowing()) {
                            progressDialog4Download.dismiss();
                        }
                        data = msg.getData();
                        String msgStr = data.getString(DownloaderConstants.DOWNLOAD_ERROR_MSG);
                        UIHelper.makeToast(mContext, msgStr);
                        finish();
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
        ProductDatainfo productDatainfo = mProductInfo.getInfo();
        productDatainfo.compInfo = mProductInfo.getCompanyInfo().getInfo();
        ProductDownloader.downloadProduct(productDatainfo, handler);
    }


    private void onLineOperation() {
        int state = ConnectionDetector.getNetStatus();
        switch (state) {
            case 1://wifi
            case 2://mobile
                initOnline();
                break;
            default:
                UIHelper.makeToast(mContext, mContext.getString(R.string.network_fail));
                finish();
                break;
        }
    }

    private void initTab() {
        //寿险百科打开产品详情
        View caseView = null;
        if (data_from == 100) {
            caseView = LayoutInflater.from(mContext).inflate(R.layout.wiki_product_detail_case_theme1, null);
        } else {
            caseView = LayoutInflater.from(mContext).inflate(R.layout.wiki_product_detail_case, null);
        }
        case_container.addView(caseView);
        initCaseView(case_container);
        setCaseInfo();
        mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.wiki_corp_vp_tab);
        mViewPager = (ViewPager) findViewById(R.id.wiki_corp_vp);
        // 设置ViewPager属性
        mAdapter = new MPagerAdapter(getSupportFragmentManager(), this, titles);
        mViewPager.setAdapter(mAdapter);
        mViewPager.setOffscreenPageLimit(4);
        // 定义 SlidingTabLayout
        mSlidingTabLayout.setDistributeEvenly(true);// 是否充满屏幕
        mSlidingTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.wiki_slidingtable_indicator_color));
        mSlidingTabLayout.setBackgroundColor(getResources().getColor(R.color.white));
        // mSlidingTabLayout.setCustomTabView(R.layout.view_tab, R.id.tv_text);
        mSlidingTabLayout.setViewPager(mViewPager); // 加载ViewPager
        mSlidingTabLayout.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                TCAgent.onEvent(mContext, "product_detail_tab", titles.get(position));
                switch (position) {
                    case 0:
                        break;
                    case 1:
                        if (!allowShowTab()) {
                            Toast.makeText(mContext, mProductObj.getInsuranceObj().getNodeInstruct(), Toast.LENGTH_SHORT).show();
                        }
                        if (frgProductTable2 != null) {
                            frgProductTable2.setmProductObj(mProductObj);
                        }
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

    /**
     * 判断利益图表tab是否可用
     *
     * @return
     */
    public boolean allowShowTab() {
        if (mProductObj.getInsuranceObj().getRateTblEnabled()) {
            return true;
        } else {
            return false;
        }
    }


    public class MPagerAdapter extends FragmentStatePagerAdapter {

        private List<String> list;

        public MPagerAdapter(FragmentManager fm, Context ctx, List<String> list) {
            super(fm);
            this.list = list;
        }

        @Override
        public Fragment getItem(int position) {

            switch (position) {

                case 0:
                    frgProductDesc = FrgProductDesc.newInstance(mProductObj, false);
                    return frgProductDesc;
                case 3:
                    frgProductRule = FrgProductRule.newInstance(mProductObj);
                    return frgProductRule;
                case 2:
                    fpc = FrgProductClause.newInstance(mProductObj.getClauseRelatedPath());
                    return fpc;
                case 1:
                    frgProductTable2 = FrgProductTable2.newInstance(allowShowTab());
                    return frgProductTable2;
                default:
                    frgProductDesc = FrgProductDesc.newInstance(mProductObj, false);
                    return frgProductDesc;
            }

        }

        @Override
        public CharSequence getPageTitle(int position) {
            String title = list.get(position);
            return title;
        }

        @Override
        public int getCount() {
            return list.size();
        }
    }


    private void toCalc() {
        Intent intent = new Intent();
        intent.setClass(ActProductDetail.this, ActWikiCalc.class);
        intent.putExtra("person", mProductObj.getPerson());
        String jsonStr = mProductObj.getFavoriteJson();
        intent.putExtra("optionString", jsonStr);
        intent.putExtra("mProductInfo", mProductInfo);
        EventBus.getDefault().postSticky(new EData4Cal(mProductObj));
        startActivity(intent);

        UserInfo userInfo = AppContext.getCurrentUser();
        Map kv = new HashMap();
        kv.put("product_name", mProductInfo.Name);
        kv.put("agentId", String.valueOf(userInfo.getUserId()));
        kv.put("account", userInfo.getUserName());
        TCAgent.onEvent(mContext, "open_calculator", "", kv);
    }

    /**
     * 案例信息
     */
    private void setCaseInfo() {
        try {
            CircleImageView avatarImageView = (CircleImageView) findViewById(R.id.avatar);
            customr_common = (TextView) findViewById(R.id.customr_common);
            customr_common.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    commonCustomerPop();
                }
            });
            int sex = Integer.parseInt(mProductObj.getPerson().sex);
            int resId = CustomerConfig.getPortraitResource(sex, mProductObj.getPerson().age);
            avatarImageView.setImageResource(resId);
            String txtT = "1".equals(mProductObj.getPerson().sex) ? "先生" : "女士";

            txtName.setText(mProductObj.getPerson().name == null ? txtT : mProductObj.getPerson().name);
            txtAge.setText(mProductObj.getPerson().age + "岁");
            txtSex.setText(mProductInfo.getAccSexStr(Integer.valueOf(mProductObj.getPerson().sex)));
            txtCate.setText(mProductInfo.getCareerCategoryCn(mProductObj.getPerson().profession) + "类职业");

            txtCname.setText(mProductInfo.ShortName);
            String txtCoverageStr = mProductObj.getCoverage() <= 0 ? "不可保" : MathUtil.getPlainDoubleStr(mProductObj.getCoverage());
            if (mProductObj.getInsuranceObj() != null && mProductObj.getInsuranceObj().isFenshu()) {
                PolicyNodeMeta node = mProductObj.getInsuranceObj().getUseAnotherFieldNameValue();
                if (node != null) {
                    EController ec = (EController) node.getEBTValue();
                    String val = ec.getSelectedName();
                    txtCoverageStr = val;
                }
            }
            txtCoverage.setText(txtCoverageStr);
            if ("不可保".equals(txtCoverageStr)) {
                viewCoverageTitle.setVisibility(View.GONE);
                viewCoverageContent.setVisibility(View.GONE);
            } else {
                viewCoverageTitle.setVisibility(View.VISIBLE);
                viewCoverageContent.setVisibility(View.VISIBLE);
            }
            //保费titile可以通过后台自定义
            String customeName = mProductObj.getInsuranceObj().getPremiumReplaceName();
            if (!DataValidation.isEmpty(customeName)) {
                txtPremiumTitle.setText(customeName);
                txtPremium.setText(MathUtil.getPlainDoubleStr(mProductObj.getPremium()));
            } else {
                txtPremium.setText(mProductObj.getPremium() <= 0 ? "不可保" : MathUtil.getPlainDoubleStr(mProductObj.getPremium()));
            }
            InsuranceObj mInsuranceObj = mProductObj.getInsuranceObj();
            List<PolicyNodeMeta> list = mInsuranceObj.getControllerNode();
            PolicyNodeMeta node = getNodeByFieldName("CoveragePeriod", list);
            EController ec = null;
            if (node != null) {
                ec = (EController) node.getEBTValue();
                txtProtect.setText(ec.getItemDisPlay()[ec.getSelectedIndex()]);
            }
            node = getNodeByFieldName("PaymentPeriod", list);
            if (node != null) {
                ec = (EController) node.getEBTValue();
                txtPP.setText(ec.getItemDisPlay()[ec.getSelectedIndex()]);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据fieldName获得单个节点
     *
     * @param
     * @return PolicyNodeMeta
     * @throws
     * @Description: 根据fieldName获得单个节点
     */
    public static PolicyNodeMeta getNodeByFieldName(String fieldName, List<PolicyNodeMeta> list) {
        if (DataValidation.isEmpty(fieldName)) {
            return null;
        }
        PolicyNodeMeta pnm = null;
        for (int i = 0; i < list.size(); i++) {
            pnm = list.get(i);
            if (pnm != null && fieldName.equalsIgnoreCase(pnm.getFieldName())) {
                return pnm;
            }
        }
        return null;
    }


    private void commonCustomerPop() {
        List<CommonCustomer> commonCustomers = dataProvider.getCommonCustomerList(5);
        if (commonCustomers == null || commonCustomers.size() <= 0) {
            UIHelper.makeToast(mContext, "无常用被保人数据");
            return;
        }
        if (mListPopupWindow != null) {
            mListPopupWindow.dismiss();
            mListPopupWindow = null;
            return;
        }
        mListPopupWindow = new ListPopupWindow(mContext);
        ListPopupWindowAdapter mListPopupWindowAdapter = new ListPopupWindowAdapter(mContext, commonCustomers);
        mListPopupWindow.setAdapter(mListPopupWindowAdapter);
        mListPopupWindow.setHeight(ListPopupWindow.WRAP_CONTENT);
        mListPopupWindow.setWidth(UIHelper.dip2px(mContext, 180));
        mListPopupWindow.setAnchorView(customr_common);
        mListPopupWindow.setModal(true);
        mListPopupWindow.setListSelector(new ColorDrawable(getResources().getColor(R.color.divider_color)));
        mListPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                mListPopupWindow.dismiss();
                CommonCustomer cc = commonCustomers.get(position);
                InsuredPerson person = new InsuredPerson();
                person.age = cc.age;
                person.sex = cc.sex + "";
                person.profession = cc.pro;
                int days = ProposalUtils.getMinAgeDay(mProductInfo);
                if (days > 0 && person.age == 0) {
                    Date bd = TimeUtils.dayPlusOrMinus(TimeUtils.getBirthday(person.age), -days);
                    person.birthday = bd;
                }
//                String tip = ProposalUtils.hasMeetWith(person, mProductInfo);
                String tip = ProposalUtils.fitMeetWith(person, mProductInfo);

                if (tip != null && tip.length() > 0) {
                    UIHelper.makeToast(mContext, tip);
                    return;
                }
                person = mProductObj.getPerson();
                person.age = cc.age;
                person.sex = cc.sex + "";
                person.profession = cc.pro;
                mProductObj.setPerson(person);
                EOnCalculatorChange epc = new EOnCalculatorChange();
                epc.isChanged = true;
                epc.mProductObj = mProductObj;
                EventBus.getDefault().post(epc);

            }
        });
        mListPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                customr_common.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.icon_arrow_down_small, 0);
            }
        });
        mListPopupWindow.show();
        customr_common.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.icon_arrow_up_small, 0);
    }

    /**
     * @param epc
     * @return void
     * @Description: 订阅被保人修改事件
     * @throw
     */
    @Subscribe
    public void onEvent(EOnCalculatorChange epc) {
        if (epc != null && epc.isChanged) {
            mProductObj = epc.mProductObj;
            //原来的流程
            if (rateHashMap == null) {
                setCaseInfo();
            } else {
                //特殊费率表流程
                getOnlineRate(mProductObj.getPerson().age, Integer.parseInt(mProductObj.getPerson().sex), mProductInfo.Id, 1);
            }
        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (progressDialog4Download != null) {
            progressDialog4Download.dismiss();
            progressDialog4Download = null;
        }
    }
}
